package com.intelligentmeterreadingsys.checkwork.activity;


import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.intelligentmeterreadingsys.MainActivity;
import com.intelligentmeterreadingsys.R;

import com.intelligentmeterreadingsys.httpserver.HttpClientServer;
import com.intelligentmeterreadingsys.httpserver.RequestUrl;
import com.intelligentmeterreadingsys.service.ReviewDataDownloadService;
import com.intelligentmeterreadingsys.service.TimingLocationService;

import com.intelligentmeterreadingsys.util.DateUtil;
import com.intelligentmeterreadingsys.util.SafetyExitUtil;
import com.intelligentmeterreadingsys.util.SharedPreferenceUtil;


import dbhelper.XmlNameHelper;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;

import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * 上下班考勤
 * @author king
 *
 */
public class CheckWorkMainActivity extends Activity {

	public static final String username = "USERNAME";// 存取用户名称标志

	public SafetyExitUtil safe=null;
   
	public static final String workstatus = "WORKSTATUS";// 上班状态
	
	public EditText edit1;// 用户姓名

	public EditText edit2;// 用户密码

	public Button button1;// 上班

	public Button button2;// 下班

	public AlertDialog pd;

    public boolean status=false;

	public String Latitude;

	public String Longitude;

	public SharedPreferenceUtil sp = null;

	public LocationClient client;
	
	public long time;
	
	public String request="上班";
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.checkworkmain);
		inti();
		addListent();
		initLocation();

	}

	/**
	 * 初始化
	 */
	public void inti() {
		edit1 = (EditText) findViewById(R.id.checkwork_username);
		edit2 = (EditText) findViewById(R.id.checkwork_pass);
		button1 = (Button) findViewById(R.id.gotowork);
		button2 = (Button) findViewById(R.id.gooffwork);
		sp = new SharedPreferenceUtil(this);
		pd = new ProgressDialog(CheckWorkMainActivity.this);
		
		String name = sp.getValue(username);
		boolean b=sp.getBoolean(workstatus);

		if (!TextUtils.isEmpty(name)) {
			edit1.setText(name);
		}
	}

	/**
	 * 添加上下班事件
	 */
	public void addListent() {

		// 上班事件
		button1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
			
				request="上班";
				Date d=new Date();
				 time=d.getTime();
				SharedPreferenceUtil sp = new SharedPreferenceUtil(
						CheckWorkMainActivity.this);
				boolean b = sp.getBoolean(workstatus);
				if (b) {
					Toast.makeText(CheckWorkMainActivity.this, "今天已打过上班卡",
							Toast.LENGTH_LONG).show();
					finish();
					return;
				}
				
					status=true;
					pd.setTitle(null);
					pd.setMessage("GPS定位中...");
					pd.show();
				if(client!=null&&!client.isStarted()){
					client.start();
				}
				
			}
		});

		// 下班事件
		button2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				//关闭自动定位服务
				Intent intent=new Intent(CheckWorkMainActivity.this, TimingLocationService.class);
				stopService(intent);
			   request="下班";
			   Date d=new Date();
				 time=d.getTime();
				SharedPreferenceUtil sp = new SharedPreferenceUtil(
						CheckWorkMainActivity.this);
				boolean b = sp.getBoolean(workstatus);
				if (!b) {
					Toast.makeText(CheckWorkMainActivity.this, "还没打上班卡！",
							Toast.LENGTH_LONG).show();
					finish();
					return;
				}
				status=false;
				pd.setTitle(null);
				pd.setMessage("GPS定位中...");
				pd.show();
              System.out.println("show");
				if (client != null && !client.isStarted()) {
					client.start();
				}
                
			

			}
		});
	}

	/**
	 * 定们监听器
	 * 
	 * @author king
	 * 
	 */
	public class Listener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location != null) {
				getLoDoubles(location);
				Toast.makeText(CheckWorkMainActivity.this,
						location.getAddrStr()+location.getLatitude(), Toast.LENGTH_LONG).show();
			}

		}

		@Override
		public void onReceivePoi(BDLocation arg0) {
			// TODO Auto-generated method stub

		}

	}

	/**
	 * 初始化定位
	 */
	public void initLocation() {
		client = new LocationClient(CheckWorkMainActivity.this);
		LocationClientOption option = new LocationClientOption();
		// 打开GPS
		option.setOpenGps(true);
		// 设置坐标类型
		option.setCoorType("bd09ll");

		// 设置网络优先
		//option.setPriority(LocationClientOption.GpsFirst);
		 option.setPriority(LocationClientOption.NetWorkFirst);

		// 设置产品线名称
		option.setProdName("waterSys");

		// 设置定位定时时间
		option.setScanSpan(50000);
		client.setLocOption(option);
		client.registerLocationListener(new Listener());

	}

	

	@Override
	protected void onDestroy() {
		System.out.println("onDestroy");
		if (client != null && client.isStarted()) {
			client.stop();
			client = null;
		}

		super.onDestroy();
	}

	

	public void getLoDoubles(BDLocation location) {
		System.out.println("得到径维度");
		Date d=new Date();
		if((d.getTime()-time)>16000){
			this.Latitude="0";
			this.Longitude="0";
			pd.setMessage("登录服务器中......");
			work(request);
		}
		if (location != null) {
			pd.setMessage("登录服务器中......");
			SharedPreferenceUtil sh=new SharedPreferenceUtil(this);
			sh.insertValue(XmlNameHelper.LATITUDE, location.getLatitude()+"");
			sh.insertValue(XmlNameHelper.LONGITUDE, location.getLongitude()+"");
			this.Latitude=location.getLatitude()+"";
			this.Longitude=location.getLongitude()+"";
			work(request);
		}

	}

	 /**
	  * 向服务端发请求
	  * @param request
	  */
	public void work(String status) {
		client.stop();
		// 得到网络服务
		HttpClientServer server = new HttpClientServer(
				CheckWorkMainActivity.this);

		// 上班传给后台参数
		Map<String, String> map = new HashMap<String, String>();
		System.out.println(edit2.getEditableText().toString()+"密码");
		map.put("name", edit1.getEditableText().toString());
		map.put("pass", edit2.getEditableText().toString());
		map.put("latitude", Latitude);
		map.put("longitude", Longitude);
		map.put("status", status);
		SharedPreferenceUtil sh=new SharedPreferenceUtil(this);
		
		map.put("imsi", sh.getValue(XmlNameHelper.IMSI));
		map.put("date", DateUtil.getBeforeDay(0));
		String respon = server.doPost(map,RequestUrl.GOTOWORK);
		if (!respon.equals("error")) {
			pd.cancel();

			try {		
				System.out.println(respon);
				JSONObject js=new JSONObject(respon);
				
				String s=js.getString("message");
						if(s.equals("no")){
							Toast.makeText(CheckWorkMainActivity.this, "密码或用户名错误", Toast.LENGTH_LONG).show();
							return;
						}else if(s.equals("yes")){
							Toast.makeText(CheckWorkMainActivity.this, "打卡成功", Toast.LENGTH_LONG).show();
							// 把用户名字存入XML
							sp.insertValue(username, edit1.getEditableText().toString());
							// 更新上下班状态
							
							 sp = new SharedPreferenceUtil(
									CheckWorkMainActivity.this);
							 SharedPreferenceUtil sp=new SharedPreferenceUtil(CheckWorkMainActivity.this);
								if(request.equals("上班")){
									  Intent intent=new Intent(CheckWorkMainActivity.this,TimingLocationService.class);
								        startService(intent);
									sp.insertValue(workstatus, true);
								}else{
									 Intent intent=new Intent(CheckWorkMainActivity.this,TimingLocationService.class);
							         stopService(intent);
									sp.insertValue(workstatus, false);
								}
								
								finish();
						}
      	} catch (JSONException e) {
				
				e.printStackTrace();
			}
	
		} else {
			Toast.makeText(CheckWorkMainActivity.this, "网络连接错误，请检查",
					Toast.LENGTH_LONG).show();
			pd.cancel();
			
		}

	}

	@Override
	protected void onPause() {
		System.out.println("text onPause");
		safe=new SafetyExitUtil(CheckWorkMainActivity.this);
		safe.start();
		
		super.onPause();
	}

	@Override
	protected void onResume() {
	   if(safe!=null){
		   safe.stop();
	   }
		
		System.out.println("text onResume ");
		super.onResume();
	}

	
       
}
